package com.zhong.blog.controller;

import com.zhong.blog.pojo.*;
import com.zhong.blog.service.BlogService;
import com.zhong.blog.service.CommentService;
import com.zhong.blog.service.ReplyService;
import com.zhong.blog.utlis.R;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.PastOrPresent;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/comment")
public class CommentController {

    @Autowired
    CommentService commentService;
    @Autowired
    BlogService blogService;
    @Autowired
    ReplyService replyService;

    @PostMapping("/save")
    public R save(@RequestBody Comment comment){
        System.out.println("=====提交评论====");
        System.out.println(comment.toString());
        commentService.save(comment);
        return R.ok();
    }
    @PostMapping("/queryByblogId")
    public R queryByblogId(@RequestParam("id") int blogid){

        System.out.println("=====查看评论====");
        List<DetailVo> detailVos = new ArrayList<>();
        List<Comment> comments = commentService.queryByblogId(blogid);

        for (Comment comment : comments) {
            DetailVo detailVo = new DetailVo();
            int commmentId = comment.getId();
            List<Reply>  replies = replyService.queryBycommentandblog(commmentId,blogid);
            BeanUtils.copyProperties(comment,detailVo);
            detailVo.setReplies(replies);
            detailVos.add(detailVo);
        }

        return R.ok().put("comments",detailVos);
    }

    @PostMapping("/reply")
    public R reply(@RequestBody Reply reply){
        System.out.println("=======提交回复评论=====");
        System.out.println(reply.toString());
        replyService.reply(reply);
        return R.ok();
    }

    @GetMapping("/getLatestComments")
    public R getLatestComments(){
        List<LatestComment> latestComments = new ArrayList<>();
        List<Comment> comments = commentService.getLatestComments();
        for (Comment comment : comments) {
            LatestComment latestComment = new LatestComment();
            BeanUtils.copyProperties(comment,latestComment);
            Blog blog = blogService.queryById(comment.getBlogid());
            latestComment.setBlog(blog);
            latestComments.add(latestComment);
        }
        return R.ok().put("latestComments",latestComments);
    }



}
